
import com.google.gson.Gson;

import java.net.*;
import java.io.*;
import java.sql.Timestamp;

/**
 * @ClassName: UDPSender
 * @Description:
 * @Author: 12071
 * @Date: 2021/6/24 16:42
 */
public class UDPSender {
    public static void main(String[] args) throws Exception
    {
        DatagramSocket ds = new DatagramSocket();//通过DatagramSocket对象创建udp服务
        BufferedReader bufr =
                new BufferedReader(new InputStreamReader(System.in));//从键盘上面输入文本
        String line = null;
        System.out.println("请输入要发送的数据");
        int id=0;
        while((line=bufr.readLine())!=null)//当输入不为空时
        {
            if("over".equals(line))//当输入为byebye时退出程序
                break;
            //确定好数据后，并把数据封装成数据包
            id++;
            Position position = new Position(1688, line, 42.0, 43.0, new Timestamp(System.currentTimeMillis()), 0);
            String json = new Gson().toJson(position);
            byte[] buf = json.getBytes();
            String address = "127.0.0.1";
            int addressPort = 8989;
            DatagramPacket dp =
                    new DatagramPacket(buf,buf.length,InetAddress.getByName(address),addressPort);//发送至指定IP，指定端口
            ds.send(dp);//通过send方法将数据包发送出去
            System.out.println("发送数据：["+json+"] 到 >> " + address+":"+addressPort);
            System.out.println("=============================");
            System.out.println("请继续输入");

        }
        ds.close();//关闭资源
    }

}
